import React, { FC, useState, useEffect } from 'react';

interface UserState {
    username: string;
    nickname: string;
}

const App: FC = () => {
    const [count, setCount] = useState<number>(() => 0);
    const [user, setUser] = useState<UserState>({
        username: '',
        nickname: '',
    });

    const [zb, setZb] = useState({ x: 0, y: 0 });

    // 执行副作用：发请求、监听事件、操作 DOM、设置本地存储、发布订阅
    useEffect(() => {
        setTimeout(() => {
            setUser({
                username: 'rui',
                nickname: '瑞',
            });
        }, 1500);
    }, []);

    const hanleClick = (e: MouseEvent) => {
        // console.log('e', e); // 如果不知道 e 的类型，可以 console.log 打印查看，再赋值类型
        setZb({
            x: e.pageX,
            y: e.pageY,
        });
    };

    // 监听事件
    useEffect(() => {
        document.addEventListener('click', hanleClick, false);

        // 如果有 return，就在返回时执行
        return () => {
            document.removeEventListener('click', hanleClick, false);
        };
    }, []); // 第二个参数如果是空，表示该 effect 不依赖任何 state

    return (
        <div className="App">
            <h3>{count}</h3>
            <button onClick={() => setCount(count + 1)}>👍 + 1</button>

            <h3>username: {user.username}</h3>
            <h3>nickname: {user.nickname}</h3>

            <h3>
                x: {zb.x}, y: {zb.y}
            </h3>
        </div>
    );
};

export default App;
